#!/bin/bash

# 交叉编译工具链配置脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 显示帮助信息
show_help() {
    echo "交叉编译工具链配置脚本"
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -a, --arch ARCH        目标架构 (arm64|arm|riscv|x86_64)"
    echo "  -t, --toolchain TOOL   工具链类型 (gcc|clang)"
    echo "  -s, --sysroot PATH     系统根目录路径"
    echo "  -o, --output FILE      输出配置文件路径"
    echo "  -h, --help             显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 -a arm64 -t gcc                    # 配置ARM64 GCC工具链"
    echo "  $0 -a riscv -t clang -s /opt/riscv    # 配置RISC-V Clang工具链"
}

# 默认参数
TARGET_ARCH=""
TOOLCHAIN="gcc"
SYSROOT=""
OUTPUT_FILE=""

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -a|--arch)
            TARGET_ARCH="$2"
            shift 2
            ;;
        -t|--toolchain)
            TOOLCHAIN="$2"
            shift 2
            ;;
        -s|--sysroot)
            SYSROOT="$2"
            shift 2
            ;;
        -o|--output)
            OUTPUT_FILE="$2"
            shift 2
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
        *)
            print_error "未知参数: $1"
            show_help
            exit 1
            ;;
    esac
done

# 检查必需参数
if [[ -z "$TARGET_ARCH" ]]; then
    print_error "请指定目标架构 (-a 参数)"
    show_help
    exit 1
fi

# 验证目标架构
case "$TARGET_ARCH" in
    arm64|arm|riscv|x86_64)
        ;;
    *)
        print_error "不支持的目标架构: $TARGET_ARCH"
        print_info "支持的架构: arm64, arm, riscv, x86_64"
        exit 1
        ;;
esac

# 验证工具链类型
case "$TOOLCHAIN" in
    gcc|clang)
        ;;
    *)
        print_error "不支持的工具链类型: $TOOLCHAIN"
        print_info "支持的工具链: gcc, clang"
        exit 1
        ;;
esac

# 设置默认输出文件
if [[ -z "$OUTPUT_FILE" ]]; then
    OUTPUT_FILE="toolchain_${TARGET_ARCH}_${TOOLCHAIN}.sh"
fi

print_info "配置交叉编译工具链..."
print_info "目标架构: $TARGET_ARCH"
print_info "工具链: $TOOLCHAIN"
print_info "系统根目录: ${SYSROOT:-"默认"}"
print_info "输出文件: $OUTPUT_FILE"

# 生成工具链配置
generate_toolchain_config() {
    local config_file="$OUTPUT_FILE"
    
    cat > "$config_file" << EOF
#!/bin/bash
# 交叉编译工具链配置文件
# 目标架构: $TARGET_ARCH
# 工具链: $TOOLCHAIN

# 目标架构配置
export TARGET_ARCH="$TARGET_ARCH"
export TARGET_OS="linux"

# 工具链前缀
case "$TARGET_ARCH" in
    arm64)
        export TOOLCHAIN_PREFIX="aarch64-linux-gnu"
        export TARGET_TRIPLET="aarch64-linux-gnu"
        ;;
    arm)
        export TOOLCHAIN_PREFIX="arm-linux-gnueabihf"
        export TARGET_TRIPLET="arm-linux-gnueabihf"
        ;;
    riscv)
        export TOOLCHAIN_PREFIX="riscv64-linux-gnu"
        export TARGET_TRIPLET="riscv64-linux-gnu"
        ;;
    x86_64)
        export TOOLCHAIN_PREFIX="x86_64-linux-gnu"
        export TARGET_TRIPLET="x86_64-linux-gnu"
        ;;
esac

# 编译器配置
if [[ "$TOOLCHAIN" == "gcc" ]]; then
    export CC="\${TOOLCHAIN_PREFIX}-gcc"
    export CXX="\${TOOLCHAIN_PREFIX}-g++"
    export AR="\${TOOLCHAIN_PREFIX}-ar"
    export AS="\${TOOLCHAIN_PREFIX}-as"
    export LD="\${TOOLCHAIN_PREFIX}-ld"
    export NM="\${TOOLCHAIN_PREFIX}-nm"
    export OBJCOPY="\${TOOLCHAIN_PREFIX}-objcopy"
    export OBJDUMP="\${TOOLCHAIN_PREFIX}-objdump"
    export RANLIB="\${TOOLCHAIN_PREFIX}-ranlib"
    export READELF="\${TOOLCHAIN_PREFIX}-readelf"
    export STRIP="\${TOOLCHAIN_PREFIX}-strip"
else
    # Clang配置
    export CC="clang"
    export CXX="clang++"
    export AR="llvm-ar"
    export AS="llvm-as"
    export LD="ld.lld"
    export NM="llvm-nm"
    export OBJCOPY="llvm-objcopy"
    export OBJDUMP="llvm-objdump"
    export RANLIB="llvm-ranlib"
    export READELF="llvm-readelf"
    export STRIP="llvm-strip"
fi

# 系统根目录
if [[ -n "$SYSROOT" ]]; then
    export SYSROOT="$SYSROOT"
    export PKG_CONFIG_SYSROOT_DIR="\$SYSROOT"
    export PKG_CONFIG_LIBDIR="\$SYSROOT/usr/lib/pkgconfig:\$SYSROOT/usr/share/pkgconfig"
fi

# 编译选项
case "$TARGET_ARCH" in
    arm64)
        export CFLAGS="-march=armv8-a -mtune=cortex-a72"
        export CXXFLAGS="-march=armv8-a -mtune=cortex-a72"
        export LDFLAGS="-Wl,--hash-style=gnu"
        ;;
    arm)
        export CFLAGS="-march=armv7-a -mfpu=neon -mfloat-abi=hard"
        export CXXFLAGS="-march=armv7-a -mfpu=neon -mfloat-abi=hard"
        export LDFLAGS="-Wl,--hash-style=gnu"
        ;;
    riscv)
        export CFLAGS="-march=rv64gc -mabi=lp64d"
        export CXXFLAGS="-march=rv64gc -mabi=lp64d"
        export LDFLAGS="-Wl,--hash-style=gnu"
        ;;
    x86_64)
        export CFLAGS="-march=x86-64 -mtune=generic"
        export CXXFLAGS="-march=x86-64 -mtune=generic"
        export LDFLAGS=""
        ;;
esac

# 通用编译选项
export CFLAGS="\$CFLAGS -O2 -Wall -Wextra -fPIC"
export CXXFLAGS="\$CXXFLAGS -O2 -Wall -Wextra -fPIC -std=c++11"

# CMake工具链文件路径
export CMAKE_TOOLCHAIN_FILE="\$(dirname "\$BASH_SOURCE")/cmake/\${TARGET_ARCH}_\${TOOLCHAIN}.cmake"

# 显示配置信息
echo "交叉编译工具链已配置:"
echo "  目标架构: \$TARGET_ARCH"
echo "  工具链: $TOOLCHAIN"
echo "  CC: \$CC"
echo "  CXX: \$CXX"
echo "  CFLAGS: \$CFLAGS"
echo "  CXXFLAGS: \$CXXFLAGS"
if [[ -n "\$SYSROOT" ]]; then
    echo "  SYSROOT: \$SYSROOT"
fi
EOF

    chmod +x "$config_file"
    print_success "工具链配置文件已创建: $config_file"
}

# 生成CMake工具链文件
generate_cmake_toolchain() {
    local cmake_dir="cmake"
    local cmake_file="$cmake_dir/${TARGET_ARCH}_${TOOLCHAIN}.cmake"
    
    mkdir -p "$cmake_dir"
    
    cat > "$cmake_file" << EOF
# CMake工具链文件
# 目标架构: $TARGET_ARCH
# 工具链: $TOOLCHAIN

set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR $TARGET_ARCH)

# 工具链前缀
if("$TARGET_ARCH" STREQUAL "arm64")
    set(TOOLCHAIN_PREFIX "aarch64-linux-gnu")
elseif("$TARGET_ARCH" STREQUAL "arm")
    set(TOOLCHAIN_PREFIX "arm-linux-gnueabihf")
elseif("$TARGET_ARCH" STREQUAL "riscv")
    set(TOOLCHAIN_PREFIX "riscv64-linux-gnu")
elseif("$TARGET_ARCH" STREQUAL "x86_64")
    set(TOOLCHAIN_PREFIX "x86_64-linux-gnu")
endif()

# 编译器设置
if("$TOOLCHAIN" STREQUAL "gcc")
    set(CMAKE_C_COMPILER \${TOOLCHAIN_PREFIX}-gcc)
    set(CMAKE_CXX_COMPILER \${TOOLCHAIN_PREFIX}-g++)
    set(CMAKE_AR \${TOOLCHAIN_PREFIX}-ar)
    set(CMAKE_RANLIB \${TOOLCHAIN_PREFIX}-ranlib)
    set(CMAKE_STRIP \${TOOLCHAIN_PREFIX}-strip)
else()
    # Clang设置
    set(CMAKE_C_COMPILER clang)
    set(CMAKE_CXX_COMPILER clang++)
    set(CMAKE_AR llvm-ar)
    set(CMAKE_RANLIB llvm-ranlib)
    set(CMAKE_STRIP llvm-strip)
endif()

# 系统根目录
if(DEFINED ENV{SYSROOT})
    set(CMAKE_SYSROOT \$ENV{SYSROOT})
    set(CMAKE_FIND_ROOT_PATH \$ENV{SYSROOT})
    set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
    set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
    set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
    set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
endif()

# 编译选项
if("$TARGET_ARCH" STREQUAL "arm64")
    set(CMAKE_C_FLAGS "-march=armv8-a -mtune=cortex-a72")
    set(CMAKE_CXX_FLAGS "-march=armv8-a -mtune=cortex-a72")
elseif("$TARGET_ARCH" STREQUAL "arm")
    set(CMAKE_C_FLAGS "-march=armv7-a -mfpu=neon -mfloat-abi=hard")
    set(CMAKE_CXX_FLAGS "-march=armv7-a -mfpu=neon -mfloat-abi=hard")
elseif("$TARGET_ARCH" STREQUAL "riscv")
    set(CMAKE_C_FLAGS "-march=rv64gc -mabi=lp64d")
    set(CMAKE_CXX_FLAGS "-march=rv64gc -mabi=lp64d")
elseif("$TARGET_ARCH" STREQUAL "x86_64")
    set(CMAKE_C_FLAGS "-march=x86-64 -mtune=generic")
    set(CMAKE_CXX_FLAGS "-march=x86-64 -mtune=generic")
endif()

# 通用编译选项
set(CMAKE_C_FLAGS "\${CMAKE_C_FLAGS} -O2 -Wall -Wextra -fPIC")
set(CMAKE_CXX_FLAGS "\${CMAKE_CXX_FLAGS} -O2 -Wall -Wextra -fPIC -std=c++11")

# 链接选项
set(CMAKE_EXE_LINKER_FLAGS "-Wl,--hash-style=gnu")
set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--hash-style=gnu")
EOF

    print_success "CMake工具链文件已创建: $cmake_file"
}

# 主函数
main() {
    generate_toolchain_config
    generate_cmake_toolchain
    
    print_success "交叉编译工具链配置完成！"
    print_info "使用方法:"
    print_info "  source $OUTPUT_FILE"
    print_info "  cmake -DCMAKE_TOOLCHAIN_FILE=cmake/${TARGET_ARCH}_${TOOLCHAIN}.cmake .."
}

# 运行主函数
main
